package com.atguigu05.communication;

/**
 * ClassName: PCC
 * Package: com.atguigu05.communication
 * Description:
 *
 * @Author BuTang
 * @Create 2023/5/16 18:55
 * @Version 1.0
 */
public class PCC {
    public static void main(String[] args) {


        Clerk c = new Clerk(0);
        Productor p1 = new Productor(c);
        // Productor p2 = new Productor(c);
        Customer cus1 = new Customer(c);
        Customer cus2 = new Customer(c);

        p1.setName("生产者1");
        //p2.setName("生产者2");
        cus1.setName("消费者1");
        cus2.setName("消费者2");
        //  p1.setPriority(Thread.MAX_PRIORITY);
        p1.start();
        //p2.start();
        cus1.start();
        cus2.start();


    }
}


/**
 * 店员
 */
class Clerk {
    private int productNum;

    public Clerk(int productNum) {
        this.productNum = productNum;
    }

    public int getProductNum() {
        return productNum;
    }

    public void addProductNum() {

        synchronized (this) {
            if (productNum < 20) {

                try {
                    notify();
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                productNum++;
                 System.out.println("生产产品"+productNum);
            } else try {
                wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public synchronized void reduceProduceNum() {

        if (productNum <= 20 && productNum > 0) {

            notify();
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            System.out.println("购买产品"+productNum);
            productNum--;
        } else {
            try {
                wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

    }
}

/**
 * 生产者
 */
class Productor extends Thread {
    private Clerk clerk;

    public Productor(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {

        while (true) {
            clerk.addProductNum();
        }
    }
}

/**
 * 消费者
 */
class Customer extends Thread {

    private Clerk clerk;

    public Customer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        while (true) {

            clerk.reduceProduceNum();
        }
    }
}
